/*
 * PixelFormat.cpp
 *
 *  Created on: 2016年1月16日
 *      Author: terry
 */

#include "PixelFormat.h"

namespace av
{

PixelFormat::PixelFormat()
{
}

PixelFormat::~PixelFormat()
{
}


struct PixelFormatEntry
{
    int fmt;
    const char *name;
    int planes;
    float width[4];
    float height[4];
    int mod_width;
    int mod_height;
} ;


const PixelFormatEntry s_formats[PixelFormat::kMAX] = {
    { PixelFormat::kNONE, "None", 0, {}, {}, 0, 0},
    { PixelFormat::kI420, "i420", 3, { 1, .5, .5 }, { 1, .5, .5 }, 2, 2 },
    { PixelFormat::kI422, "i422", 3, { 1, .5, .5 }, { 1,  1,  1 }, 2, 1 },
    { PixelFormat::kI444, "i444", 3, { 1,  1,  1 }, { 1,  1,  1 }, 1, 1 },
    { PixelFormat::kYV12, "yv12", 3, { 1, .5, .5 }, { 1, .5, .5 }, 2, 2 },
    { PixelFormat::kNV12, "nv12", 2, { 1,  1 },     { 1, .5 },     2, 2 },
    { PixelFormat::kBGR,  "bgr",  1, { 3 },         { 1 },         1, 1 },
    { PixelFormat::kBGRA, "bgra", 1, { 4 },         { 1 },         1, 1 },
    { PixelFormat::kRGB,  "rgb",  1, { 3 },         { 1 },         1, 1 },
    { PixelFormat::kYUY2, "yuy2", 1, { 1.5 },         { 1 },         1, 1 },
    { PixelFormat::kUYVY, "uyvy", 1, { 1.5 },         { 1 },         1, 1 },
    { PixelFormat::kRGB32, "rgb32", 1, { 4 },         { 1 },         1, 1 },

};


bool isValidColorSpace(int fmt)
{
    return (fmt > 0 && fmt < PixelFormat::kMAX);
}



int PixelFormat::getPicturePlaneSize(int fmt, int width, int height, int plane)
{
    double size = width * height;

    size *= s_formats[fmt].width[plane];
    size *= s_formats[fmt].height[plane];

    return (int)size;
}

int PixelFormat::getPictureSize(int fmt, int width, int height)
{
    if (!isValidColorSpace(fmt))
    {
        return 0;
    }

    int size = 0;
    for (int i = 0; i < s_formats[fmt].planes; ++ i)
    {
        size += getPicturePlaneSize(fmt, width, height, i);
    }
    return size;
}


const char* PixelFormat::getName(int fmt)
{
    if (!isValidColorSpace(fmt))
    {
        return s_formats[0].name;
    }
    return s_formats[fmt].name;
}

int PixelFormat::parseName(const char* name)
{
    for (size_t i = 0; i < PixelFormat::kMAX; ++ i)
    {
        if (strcmp(name, s_formats[i].name) == 0)
        {
            return i;
        }
    }
    return PixelFormat::kNONE;
}




} /* namespace av */
